package cn.owng.cli.gen;

import cn.owng.cli.Env;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import picocli.CommandLine;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@CommandLine.Command(name = "mp", description = "Mybatis-Plus 代码生成工具")
public class GenMp implements Callable<Integer> {

    /**
     * 需要生成代码的表
     */
    @CommandLine.Option(names = {"-t", "--tables"}, description = "表名, 可用多个 -t, 例如: -t user -t role")
    private List<String> tables;

    @Override
    public Integer call() throws Exception {
        Env.Db db = Env.db();
        String finalProjectPath = "target/generated";
        FastAutoGenerator.create(String.format("%s/%s?%s", db.getUrl(), db.getDatabase(), db.getQuery()), db.getUsername(), db.getPassword())
                .globalConfig(builder -> builder.disableOpenDir().dateType(DateType.ONLY_DATE).outputDir(finalProjectPath + "/src/main/java"))
                .packageConfig(builder -> builder.parent("cn.owng.server.common.generated"))
                .strategyConfig(builder -> {
                    builder.controllerBuilder().enableFileOverride()
                            .mapperBuilder().enableFileOverride()
                            .serviceBuilder().enableFileOverride()
                            .entityBuilder().enableTableFieldAnnotation()
                            .idType(IdType.ASSIGN_ID)
                            .enableFileOverride()
                            .enableLombok()
                            .enableChainModel()
                            .enableActiveRecord();

                    if (tables == null || tables.isEmpty()) {
                        builder.addExclude("flyway_migrate");
                    } else {
                        builder.addInclude(tables);
                    }
                }).templateEngine(new FreemarkerTemplateEngine()).execute();
        return 0;
    }
}
